package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.exception.GuliException;
import com.guli.edu.entity.Course;
import com.guli.edu.entity.CourseDescription;
import com.guli.edu.entity.GuliMsg;
import com.guli.edu.form.CourseInfoForm;
import com.guli.edu.mapper.CourseDescriptionMapper;
import com.guli.edu.mapper.CourseMapper;
import com.guli.edu.mapper.GuliMsgMapper;
import com.guli.edu.query.CourseQuery;
import com.guli.edu.service.CourseService;
import com.guli.edu.vo.CoursePublishVo;
import com.guli.edu.vo.CourseWebVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Frank
 * @since 2019-04-15
 */
@Slf4j
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private CourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private GuliMsgMapper guliLogMapper;

    @Transactional
    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        //保存课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        baseMapper.insert(course);

        //保存课程描述信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.insert(courseDescription);

        return course.getId();
    }

    @Override
    public CourseInfoForm getCourseFormInfoById(String id) {
        //查询course表
        Course course = baseMapper.selectById(id);

        if (Objects.isNull(course)) {
            throw new GuliException(20001, "数据不存在");
        }

        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);
        if (Objects.isNull(courseDescription)) {
            throw new GuliException(20001, "数据不完整");
        }

        CourseInfoForm courseInfoForm = new CourseInfoForm();
        BeanUtils.copyProperties(course, courseInfoForm);
        courseInfoForm.setDescription(courseDescription.getDescription());

        return courseInfoForm;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {
        long startTimeMilli = System.currentTimeMillis();
        //修改课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        baseMapper.updateById(course);

        //修改课程详情信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.updateById(courseDescription);

    }

    @Override
    public void pageQuery(Page<Course> pageParam, CourseQuery courseQuery) {

        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();

        if (Objects.isNull(courseQuery)) {
            baseMapper.selectPage(pageParam, courseQueryWrapper);
            return;
        }

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)) {
            courseQueryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            courseQueryWrapper.eq("teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            courseQueryWrapper.eq("subject_parent_id", subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)) {
            courseQueryWrapper.eq("subject_id", subjectId);
        }

        baseMapper.selectPage(pageParam, courseQueryWrapper);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCourseById(String id) {
        //删除课程记录
        baseMapper.deleteById(id);
        //删除课程描述记录
        courseDescriptionMapper.deleteById(id);

    }


    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return baseMapper.selectCoursePublishVoById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void publishCourseById(String id) {
        Course course = new Course();
        course.setId(id);
        course.setStatus(Course.COURSE_NORMAL);
        baseMapper.updateById(course);

//
//        try {
//
//            //课程发布成功后向讲师发送短信，
//            CourseService courseServiceProxy = (CourseService) AopContext.currentProxy();
//            courseServiceProxy.sendMsg("您的课程已发布", "1111");
//           //sendMsg("您的课程已发布", "1111");
//        } catch (Exception e) {
//            log.error("短信发送异常" + e.getMessage());
//        }
//
//        log.info("=============== end publishCourseById  ==============");

    }

    /**
     * 模拟发送短信
     *
     * @param msg log message
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sendMsg(String msg, String teacherId) {
        log.info("=============== start send msg ==============");

        GuliMsg guliMsg = new GuliMsg();
        guliMsg.setId(teacherId);
        guliMsg.setText(msg);

        try {
            //延迟2秒 方便测试
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //写入数据库
        guliLogMapper.insert(guliMsg);
        //打印线程及日志到控制台
        log.error(Thread.currentThread() + "");


        //调用接口发送短信
        throw new GuliException(22000, "短信发送失败");

    }

    @Override
    public List<Course> selectByTeacherId(String teacherId) {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.orderByAsc("gmt_modified");
        courseQueryWrapper.eq("teacher_id", teacherId);
        return baseMapper.selectList(courseQueryWrapper);

    }

    @Override
    public Map<String, Object> pageListWeb(Page<Course> coursePageParam) {

        Map<String, Object> courseMap = new HashMap<>();
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.orderByAsc("gmt_modified");
        baseMapper.selectPage(coursePageParam, courseQueryWrapper);

        List<Course> records = coursePageParam.getRecords();
        long pages = coursePageParam.getPages();
        long total = coursePageParam.getTotal();
        long current = coursePageParam.getCurrent();
        long size = coursePageParam.getSize();
        boolean hasPrevious = coursePageParam.hasPrevious();
        boolean hasNext = coursePageParam.hasNext();

        courseMap.put("items", records);
        courseMap.put("pages", pages);
        courseMap.put("total", total);
        courseMap.put("current", current);
        courseMap.put("size", size);
        courseMap.put("hasPrevious", hasPrevious);
        courseMap.put("hasNext", hasNext);
        return courseMap;

    }

    @Transactional
    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);

        return baseMapper.selectInfoWebById(id);

    }

    @Override
    public void updatePageViewCount(String id) {
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }
}
